package com.hh.tipsumfirst

import android.content.Context
import android.provider.Settings
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

object MD5Utils {

    fun getID(context: Context): String{
        return getMD5(getUUID(context))
    }

    private fun getUUID(context: Context): String{
        var uuid = getAndroidID(context)
        if (uuid.isNotEmpty()){
            uuid = "实时金额" + UUID.nameUUIDFromBytes(uuid.toByteArray()).toString().replace("-", "")
        }
        return uuid
    }

    private fun getAndroidID(context: Context): String {
        var id = ""
        try {
            id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)
        }catch (e: Exception){
            e.printStackTrace()
        }
        return id
    }

    /**
     * MD5加密，获得32位字符串(小写)
     * @param password
     * @return
     */
    fun getMD5(password: String): String {
        var mStr = "shishi" + password + "jine"
        try {
            // 得到一个信息摘要器
            val digest = MessageDigest.getInstance("md5")
            val result = digest.digest(mStr.toByteArray())
            val buffer = StringBuffer()
            // 把每一个byte 做一个与运算 0xff;
            for (b in result) {
                // 与运算
                val number = b.toInt() and 0xff // 加盐
                val str = Integer.toHexString(number)
                if (str.length == 1) {
                    buffer.append("0")
                }
                buffer.append(str)
            }

            // 标准的md5加密后的结果
            mStr = buffer.toString()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return  mStr
    }
}